//
//  CWCPhotoDetailViewController.m
//  ChuanNews
//
//  Created by dllo on 16/4/25.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CWCPhotoDetailViewController.h"
#import "BaseHeader.h"
#import "UIImageView+WebCache.h"
#import "CWCAllPanBack.h"
typedef void(^LoadBlock)(id);
#define STATUS_HEIGHT [UIApplication sharedApplication].statusBarFrame.size.height
#define NC_HEIGHT self.navigationController.navigationBar.frame.size.height
#define TABBAR_HEIGHT self.tabBarController.tabBar.frame.size.height
@interface CWCPhotoDetailViewController ()<UIScrollViewDelegate,UIGestureRecognizerDelegate>
@property(nonatomic, retain)UIScrollView *mainView;
@end

@implementation CWCPhotoDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];

    self.mainView = [[CWCAllPanBack alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    self.mainView .backgroundColor= [UIColor blackColor];
    self.mainView.pagingEnabled = YES;
    self.mainView.contentSize = CGSizeMake(WIDTH, HEIGHT);
    [self.view addSubview:self.mainView];
    [self.mainView release];
    [self.mainView.panGestureRecognizer requireGestureRecognizerToFail:[self screenEdgePanGestureRecognizer]];
    self.photsArray = [NSMutableArray array];
    self.textArray = [ NSMutableArray array];
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://c.3g.163.com/photo/api/set/%@.json",self.setid]];
    [self loadDataWithUrl:url byHandle:^(NSMutableDictionary * dataDic){
        NSArray *array = dataDic[@"photos"];
        for (NSDictionary *dic in array) {
            CWCPhotoDetailModel *model = [[CWCPhotoDetailModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.photsArray addObject:model];
            [self.textArray addObject:model.note];
            [model release];
        }
        self.mainView.contentSize = CGSizeMake((self.photsArray.count) * CGRectGetWidth(self.mainView.frame), 0);
        CustomView *custV_1 = [[ CustomView alloc]initWithFrame:CGRectMake(0 , 0, WIDTH, HEIGHT - NC_HEIGHT - STATUS_HEIGHT - TABBAR_HEIGHT)];
        custV_1.tag = 1000;
        [self.mainView addSubview:custV_1];
        CWCPhotoDetailModel *photo_1 = (CWCPhotoDetailModel *)self.photsArray[0];
        MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:custV_1];
        [custV_1 addSubview:hud];
        hud.mode = MBProgressHUDModeIndeterminate;
        [hud show:YES];
        [custV_1.imageView sd_setImageWithURL:[NSURL URLWithString:photo_1.imgurl]placeholderImage:[UIImage imageNamed:@""] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [hud hide:YES];
        }];
        for (int i = 1; i < self.photsArray.count; i++) {
            CustomView *customView = [[CustomView alloc]initWithFrame:CGRectMake(i * CGRectGetWidth(self.mainView.frame), 0, WIDTH, HEIGHT - NC_HEIGHT - STATUS_HEIGHT - TABBAR_HEIGHT)];
            customView.tag = 1000 + i;
            [self.mainView addSubview:customView];
            [customView release];
        }
        [self setupViews];
        
        self.imgsumLabel.text = [NSString stringWithFormat:@"/%@",[dataDic objectForKey:@"imgsum"]];
        self.imgsumLabel.frame = CGRectMake(WIDTH - 10 - 25, HEIGHT - TABBAR_HEIGHT - WIDTH / 3.6, 25, WIDTH / 20);
        self.imgNumLabel.frame = CGRectMake(self.imgsumLabel.frame.origin.x - 25, HEIGHT - TABBAR_HEIGHT - WIDTH / 3.6, 22, WIDTH / 20);
        self.setnameLabel.text = [dataDic objectForKey:@"setname"];
        self.noteText.text = self.textArray[0];
        self.mainView.delegate = self;
    }];
    
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    
}


-(void)setupViews{
    //标题lable
    self.setnameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, HEIGHT - TABBAR_HEIGHT - WIDTH / 3.6 ,WIDTH - (WIDTH / 10) - 10, WIDTH / 20)];
    //设置属性
    self.setnameLabel.textColor = [UIColor whiteColor];
    self.setnameLabel.font = [UIFont systemFontOfSize:20];
    
    //图片数量label
    self.imgsumLabel = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH - 10) - WIDTH / 40, _setnameLabel.frame.origin.y, WIDTH / 40, WIDTH / 20)];
    //设置属性
    self.imgsumLabel.textColor = [UIColor whiteColor];
    self.imgsumLabel.font = [UIFont systemFontOfSize:14];
    
    //图片下标label
    self.imgNumLabel= [[UILabel alloc] initWithFrame:CGRectMake(_label.frame.origin.x - WIDTH/40,  _label.frame.origin.y, WIDTH/40, self.imgsumLabel.frame.size.height)];
    self.imgNumLabel.textColor = [UIColor whiteColor];
    self.imgNumLabel.textAlignment = NSTextAlignmentRight;
    self.imgNumLabel.font = [UIFont systemFontOfSize:18];
    
    self.imgNumLabel.text = @"1";
    
    //图片详情textView
    self.noteText = [[UITextView alloc] initWithFrame:CGRectMake(5, self.setnameLabel.frame.origin.y + self.setnameLabel.frame.size.height + WIDTH/200, WIDTH - 10, WIDTH / 3.8)];
    
    self.noteText.backgroundColor = [UIColor clearColor];
    self.noteText.textColor = [UIColor whiteColor];
    self.noteText.font = [UIFont systemFontOfSize:14];
    self.noteText.editable = NO;
    self.noteText.selectable = NO;
    
    
    
    
    [self.view addSubview:self.setnameLabel];
    [self.view addSubview:self.imgsumLabel];
    [self.view addSubview:self.imgNumLabel];
    [self.view addSubview:self.label];
    [self.view addSubview:self.noteText];
    [self.setnameLabel release];
    [self.imgNumLabel release];
    [self.imgsumLabel release];
    [self.label release];
    [self.noteText release];
}

-(void)loadDataWithUrl:(NSURL *)url byHandle:(LoadBlock)handle{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(queue, ^{
        //请求对象
        NSData *data=[NSData dataWithContentsOfURL:url];
        
        if (!data) {
            return ;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSMutableDictionary * dic =[NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            
            handle(dic);
        });
    });
}

-(UIScreenEdgePanGestureRecognizer *)screenEdgePanGestureRecognizer{
    UIScreenEdgePanGestureRecognizer *screenEdgePanGestureRecognizer = nil;
    if (self.navigationController.view.gestureRecognizers.count > 0)
    {
        for (UIGestureRecognizer *recognizer in self.navigationController.view.gestureRecognizers)
        {
            if ([recognizer isKindOfClass:[UIScreenEdgePanGestureRecognizer class]])
            {
                screenEdgePanGestureRecognizer = (UIScreenEdgePanGestureRecognizer *)recognizer;
                break;
            }
        }
    }
    return screenEdgePanGestureRecognizer;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x / WIDTH;
    CGFloat maxOff = WIDTH * (self.textArray.count - 1);
    BOOL flag = scrollView.contentOffset.x <= maxOff;
    CGFloat offset = ((NSInteger)scrollView.contentOffset.x) % ((NSInteger)WIDTH);
    CGFloat per = offset / WIDTH;
    if (flag) {
        self.imgNumLabel.text = [NSString stringWithFormat:@"%d",(int)index + 1];
        int i = [self.imgNumLabel.text intValue];
        self.noteText.text = self.textArray[i - 1];
        self.imgNumLabel.alpha = 1;
        self.noteText.alpha = 1;
        self.setnameLabel.alpha = 1;
        self.imgsumLabel.alpha = 1;
    }else{
        [UIView animateWithDuration:0.5 animations:^{
            self.imgNumLabel.alpha = 1 - per;
            self.imgsumLabel.alpha = 1 - per;
            self.noteText.alpha = 1 - per;
            self.setnameLabel.alpha = 1 - per;
        }];
        if (index == self.textArray.count) {
            self.imgNumLabel.alpha = 0;
            self.imgsumLabel.alpha = 0;
            self.setnameLabel.alpha = 0;
            self.noteText.alpha = 0;
        }
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame);
        CustomView *customViewA = (CustomView *)[self.view viewWithTag:1000 + index + 1];
        CustomView *customViewB = (CustomView *)[self.view viewWithTag:1000+index - 1];
        customViewB.zoomScale = 1;
        [customViewB resetFrame];
        customViewA.zoomScale = 1;
        [customViewA resetFrame];
    
    [self loadImageAtIndex:index];
}

-(void)loadImageAtIndex:(NSInteger)index{
    if (index > 0 && index < self.photsArray.count) {
        CWCPhotoDetailModel *model = self.photsArray[index];
        CustomView *imgScrollView = (CustomView *)[self.view viewWithTag:1000 + index];
        if (!imgScrollView.imageView.image) {
            MBProgressHUD * hud = [[MBProgressHUD alloc]initWithView:imgScrollView];
            [imgScrollView addSubview:hud];
            [hud show:YES];
            [imgScrollView.imageView sd_setImageWithURL:[NSURL URLWithString:model.imgurl]placeholderImage:[UIImage imageNamed:@""] options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                [hud hide:YES];
            }];
        }
    }
}
-(void)dealloc{
    [_setnameLabel release];
    [_imgNumLabel release];
    [_imgsumLabel release];
    [_noteText release];
    [_label release];
    [_photo release];
    [_mainView release];
    [super dealloc];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
